<?php
/**
 * Created by PhpStorm.
 * User: gm
 * Date: 2018/12/11
 * Time: 19:15
 */
include "config.php";
include "status.php";
if($_SERVER["REQUEST_METHOD"]=="POST"){
    $UID=$_REQUEST["u_id"];
    $GID=$_REQUEST["gid"];
    $CNAME=$_REQUEST["goodsName"];
    $CPRICE=$_REQUEST["newPrice"];
    $CNUM=$_REQUEST["num"];
    $CIMG=$_REQUEST["img"];
    $CTOTAL=$CPRICE*$CNUM;
    $sqlQuery="SELECT * FROM cart WHERE u_id=?";
    $stmtQ=$conn->prepare($sqlQuery);
    $stmtQ->bind_param("s",$UID);
    $stmtQ->execute();
    $queryRes=$stmtQ->get_result();
    $flag=true;
    while ($row=$queryRes->fetch_assoc()){
        if($row["g_id"]==$GID){
            $flag=false;
            break;
        }
    }
    $stmtQ->close();
    if($flag==true){
        $sqlInsert="INSERT INTO cart (c_name,c_price,c_num,c_total,c_img,u_id,g_id)VALUES(?,?,?,?,?,?,?);";
        $stmtI=$conn->prepare($sqlInsert);
        $stmtI->bind_param("siiisii",$CNAME,$CPRICE,$CNUM,$CTOTAL,$CIMG,$UID,$GID);
        $stmtI->execute();
        if($stmtI->affected_rows>=1){
            print_r(json_encode(Status::$i_s));
        }else{
            print_r(json_encode(Status::$i_f));
        }
        $stmtI->close();
    }else{
        $sqlUpdate="UPDATE cart SET c_num=c_num+?,c_total=c_num*c_price WHERE u_id=? AND g_id=?;";
        $stmtU=$conn->prepare($sqlUpdate);
        $stmtU->bind_param("iii",$CNUM,$UID,$GID);
        $stmtU->execute();
        if($stmtU->affected_rows>=1){
            print_r(json_encode(Status::$u_s));
        }else{
            print_r(json_encode(Status::$u_f));
        }
        $stmtU->close();
    }
    $conn->close();
}else{
    print_r(json_encode(Status::$no_get));
}